package cn.bsuc.crm.controller;

import cn.bsuc.crm.entity.Customer;
import cn.bsuc.crm.service.CustomerService;
import cn.bsuc.crm.util.Code;
import cn.bsuc.crm.util.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhuoyuan
 * @since 2022-10-03
 */
@RestController
@CrossOrigin
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @RequestMapping("/getPage")
    public Result getPage(Customer customer,@RequestParam(defaultValue = "1") int pageNo,
                          @RequestParam(defaultValue = "4") int pageSize) {
        try {
            PageInfo<Customer> PageInfo = customerService.getPage(customer,pageNo,pageSize);
            return Result.ok(PageInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(Code.SYSTEM_ERR, "系统出错");
    }
    @RequestMapping("/save")
    public Result save(Customer customer) {
        try {
            int r = customerService.saveCustomer(customer);
            if (r > 0) {
                return Result.ok();
            } else {
                return Result.fail(Code.ERROR, "保存失败");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return Result.fail(Code.SYSTEM_ERR, "系统出错");
    }

    @RequestMapping("/delById")
    public Result delById(Integer id) {
        try {
            int r = customerService.deleteById(id);
            if (r > 0) {
                return Result.ok();
            } else {
                return Result.fail(Code.ERROR, "删除失败");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return Result.fail(Code.SYSTEM_ERR, "系统出错");
    }

    @RequestMapping("/selById")
    public Result selById(Integer id) {
        try {
            Customer customer = customerService.selectById(id);
            if (customer !=null) {
                return Result.ok(customer);
            } else {
                return Result.fail(Code.ERROR, "没有该用户！！！");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return Result.fail(Code.SYSTEM_ERR, "系统出错");
    }




}

